package com.zy.yun.core.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zy.yun.base.constant.Const;
import com.zy.yun.base.entity.User;
import com.zy.yun.utils.RedisUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: 王彦委
 * @Description:
 * @Date: 21:51 2019/11/6
 */
@Component
public class CustomZuulFilter extends ZuulFilter {


    @Autowired
    private RedisUtil<User,List> redisUtil;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getHeader("Authorization");

        //判断token是否为空，
        if (StringUtils.isBlank(token)) {
            return null;
        }

        //获取当前url
        String uri = request.getRequestURI();
        //获取需要验证的资源
        List resList = redisUtil.getMapObject2(Const.DATABASE_NAME, Const.TABLE_SYS_RES, List.class);

        if (CollectionUtils.isEmpty(resList)) {
            return null;
        }
        for (Object o : resList) {
            JSONObject res = (JSONObject) o;
            if (uri.equalsIgnoreCase(res.getString("url"))) {
                //查询用户权限中是否包含对uri的访问权限
                if (!isContainsUri(token, uri, res.getLong("id"))) {
                    currentContext.getResponse().setContentType("text/html;charset=UTF-8");
                    currentContext.setResponseBody("您没有权限！");
                    currentContext.setResponseStatusCode(403);
                    currentContext.setSendZuulResponse(false);
                    return null;
                }
            }
        }
        return null;
    }

    /**
     * @Author: 王彦委
     * @Description: 验证自己的权限中是否包含 本次请求的uri
     * @Date: 17:21 2019/11/7 0007
     */
    private boolean isContainsUri(String token, String uri, Long resId) {

        //根据token,查询用户信息
        User user = redisUtil.getMapObject(Const.TOKEN_MAP_NAME, token, User.class);
        //获取角色资源
        List roleResList = redisUtil.getMapObject2(Const.DATABASE_NAME, Const.TABLE_SYS_ROLE_RES, List.class);
        for (Object obj : roleResList) {
            JSONObject roleRes = (JSONObject) obj;
            if (user.getRoleId().equals(roleRes.getLong("roleId")) && roleRes.getLong("resId").equals(resId)) {
                return true;
            }
        }

        return false;
    }
}
